package com.dkm.interceptor;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.dkm.entity.Users;
import com.dkm.util.RedisUtil;
import com.dkm.util.TokenUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    //注入redis工具类
    @Autowired
    private RedisUtil redisUtil;


    @Override 
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //从header中获取token
        String token = request.getHeader("token");

        //判断获取到的token是否为空
        if (token != null && token != ""){
            try {
                //根据传来的token，解析出用户
            	Users user = TokenUtil.unsign(token, Users.class);
                //根据解析出的用户从redis里取出token
                Object o = redisUtil.get(user.getLogin_name());
                //判断redis里的token是否过期
                if (o != null){
                    //判断两个token是否相等
                    if (token.equals(o)) {
                        return true;
                    }
                }
            } catch (Exception e) { }
        }

        //返回输出格式
        JSONObject json = new JSONObject();
        json.put("success", "false");
        json.put("msg", "认证失败");
        json.put("code", "500");
        response.getWriter().append(json.toString());
        System.out.println("认证失败");

        return false;
    }
}
